using System;
using System.Linq;

namespace NHCourse.Models
{
   public class JQGridModel<T>
   {
      public JQGridModel(int pageSize, int currentPage, IQueryable<T> query, Func<T, int> idSelector, Func<T, string[]> cellSelector)
      {
         pageSize = Math.Max(pageSize, 1);
         currentPage = Math.Max(currentPage, 1);

         var totalRows = query.Count();
         var totalPages = (int)Math.Ceiling((double)totalRows / pageSize);

         total = totalPages;
         page = Math.Min(totalPages, currentPage);
         records = totalRows;
         rows = query
            .Skip((Math.Max(page, 1) - 1) * pageSize)
            .Take(pageSize)
            .Select(row => new JQGridRowModel(idSelector(row), cellSelector(row)))
            .ToArray();
      }

      public int total { get; private set; }
      public int page { get; private set; }
      public int records { get; private set; }
      public JQGridRowModel[] rows { get; private set; }
   }

   public class JQGridRowModel
   {
      public JQGridRowModel(int id, string[] cell)
      {
         this.id = id;
         this.cell = cell;
      }

      public int id { get; private set; }
      public string[] cell { get; private set; }
   }
}